package com.work.chat.custom.server.config.exception;


import com.work.chat.common.util.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 自定义异常处理器
 * @author admin
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response notFount(RuntimeException e) {
        log.error("运行时异常:{}", e.getMessage(),e);
        return Response.buildError("运行时异常:" + e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handleException(Exception e) {
        log.error("服务器错误:{}", e.getMessage(),e);
        return Response.buildError("服务器错误，请联系管理员");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Response handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return Response.buildError("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 非法参数异常
     * @param e
     * @return
     */
    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Response illegalArgumentExceptionHandler(IllegalArgumentException e) {
        log.error(e.getMessage(), e);
        return Response.buildError(e.getMessage());
    }


    /**
     * 校验注解参数异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Response exceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMessage = new StringBuilder("");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage.append(fieldError.getDefaultMessage() + "!");
        }
        return Response.buildError(errorMessage.toString());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(BizException.class)
    @ResponseStatus(HttpStatus.OK)
    public Response businessException(BizException e) {
        log.error(e.getMessage(), e);
        return Response.buildCodeAndMsg(e.getCode(), e.getMessage());
    }


}